﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WallController : MonoBehaviour
{

    // 准备用来生成的对象
    public GameObject walls;

    // 登录所有的墙壁
    private GameObject[] sceneWalls;
    
    // 一次滚动出现几组墙壁
    public int wallNum = 8;


    // 墙壁生成的最低高度
    public float wallMinHeight = -1f;

    // 墙壁生成的最高高度                  
    public float wallMaxHeight = 3.5f;

    // 场景宽度(一次滚动的单位)
    public float stageWidth = 20.48f;
    
    // 当前柱子的索引
    private int currentWallIndex = 0;

    void Start()
    {

        sceneWalls = new GameObject[wallNum];


        // 循环生成墙壁的位置
        for (int i = 0; i < wallNum; i++) {
            // 随机生成的高度
            float spawnYPosition = Random.Range (wallMinHeight, wallMaxHeight);

            // 利用Instantiate函数在场景中重复生成多个游戏对象，按照一定间隔分开两个屏幕(一轮滚动)之间保持距离
            GameObject obj = (GameObject) Instantiate (walls, new Vector3 ((stageWidth * 2 / wallNum) * (i + 1), spawnYPosition, 0.0f), Quaternion.identity);
          
            sceneWalls[i] = obj;
        }
        
    }

    // Update is called once per frame
    void Update()
    {
         if (sceneWalls[currentWallIndex].transform.position.x < -stageWidth) {

             Debug.Log("刷新新的柱子");
             // 随机生成的高度
            float spawnYPosition = Random.Range (wallMinHeight, wallMaxHeight);
            sceneWalls[currentWallIndex].transform.position = new Vector3 (stageWidth, spawnYPosition, 0);

            // 开始计算下一堵墙
            currentWallIndex++;

            // 数组越界了的话
            if (currentWallIndex >= wallNum) {
                 // 回归到计算第一个墙壁的位置
                currentWallIndex = 0;
            }

         }
        
    }
}
